import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as apiLogin, getUserInfo } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
    const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
    const token = ref(localStorage.getItem('token') || '')

    // 计算属性
    const isLoggedIn = computed(() => !!userInfo.value.username && !!token.value)
    const isAdmin = computed(() => Array.isArray(userInfo.value.roles) && userInfo.value.roles.some(r => r?.toUpperCase()?.includes('ADMIN')))
    const isStaff = computed(() => !isAdmin.value)
    const userName = computed(() => userInfo.value.name || userInfo.value.realName || userInfo.value.username || '用户')

    // 登录方法
    const login = async ({ username, password }) => {
        try {
            const res = await apiLogin({ username, password })
            // 后端返回 { token, user: { id, username, name, ... }, roles }
            token.value = res.token
            const roles = res.roles || []
            userInfo.value = { ...res.user, roles }

            localStorage.setItem('token', token.value)
            localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
            return userInfo.value
        } catch (error) {
            throw error
        }
    }

    // 退出登录
    const logout = async () => {
        userInfo.value = {}
        token.value = ''
        localStorage.removeItem('userInfo')
        localStorage.removeItem('token')
    }

    return {
        userInfo,
        user: userInfo, // 添加user别名以保持兼容性
        token,
        isLoggedIn,
        isAdmin,
        isStaff,
        userName,
        login,
        logout
    }
})